﻿$.package("ayatta.seller.item", function () {

    var me = this;
    var model = {};

    me.NameOnKeyup = function (obj) {
        var val = obj.value = obj.value.replace(/[^\u4e00-\u9fa5\A-Za-z0-9\-\/\.\'\s]/g, '')
         .replace(/\-+/g, '-').replace(/\/+/g, '/').replace(/\.+/g, '.').replace(/\'+/g, '\'').replace(/\s+/g, ' ')
         .replace(/^[\-\/\.\']/g, '').replace(/(^s*)|(s*$)/g, "");
       
        var len = val.Length("gbk");
        if (len > 60) {
            $(obj).next('.help-block').addClass('.text-danger');
            return;
        }
        var x = 60 - len;
        $('#item-name-len').html('还可以输入' + x + '字节');
    }

    me.NameOnBlur = function (obj) {
        var val =obj.value = obj.value.replace(/[\-\/\.\']$/g, '');
       
        var len = val.Length("gbk");
        if (len > 60) {
            $(obj).next('.help-block').addClass('.text-danger');
            return;
        }
        var x = 60 - len;
        $('#item-name-len').html('还可以输入' + x + '字节');
    }

    me.PriceOnKeyup = function (obj) {
        obj.value = obj.value.replace(/[^0-9\.]/g, '');
    }

    me.PriceOnBlur = function (obj) {
        var val = obj.value.replace(/[^0-9\.]/g, '').replace(/^[\.]/g, '').replace(/[\.*]$/g, '');

        var reg = /^-?\d+(\.\d{1,2})?$/
        if (!reg.test(val)) {
            obj.value = val = val == '' ? 0 : parseFloat(val);
        }
        else {
            obj.value = val;
        }

        var name = obj.name || '';
        if (name == 'prop.price') {
            var price = $(obj).data("price") || { min: 0, max: 999999999 };

            if (val < price.min || val > price.max) {
                obj.value = price.min;
            }
        }
        else {
            var prices = [];

            var array = $('.sku-price');

            $.each(array, function (i, o) {
                var price = $(o).val();
                if (reg.test(price)) {
                    prices.push(price);
                }
            });
            var min = _.min(prices);
            var max = _.max(prices);
            var data = { min: min, max: max };
            $("input[name='prop.price']").val(min).data("price", data);
        }
    }


    me.QuantityOnKeyup = function (obj) {
        obj.value = obj.value.replace(/\D/g, '');
    }

    me.QuantityOnBlur = function (obj) {
        var val = obj.value = obj.value.replace(/\D/g, '');
        obj.value = val = val == '' ? 0 : parseInt(val);

        var name = obj.name || '';
        if (name != 'prop.quantity') {

            var sum = 0;
            var array = $('.sku-quantity');

            $.each(array, function (i, o) {
                var quantity = $(o).val();
                if (quantity != '') {
                    sum += parseInt(quantity);
                }
            });
            $("input[name='prop.quantity']").val(sum);
        }       
    }
});

